package com.zht.controller;

import com.zht.constant.Constant;
import com.zht.entity.FileUrlEntity;
import com.zht.entity.FileVo;
import com.zht.result.AjaxResult;
import com.zht.service.SendMessageService;
import com.zht.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传下载服务器
 *
 * @author zhaoht
 * @date 2024/6/6
 */
@RestController
@RequestMapping("/zht/file")
public class FileUploadDownLoadController {

    //日志
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //上传文件url
    private Path fileUploadPath = Paths.get(FileUrlEntity.getFilePath());

    @Autowired
    private SendMessageService sendMessageService;

    /**
     * 上传文件
     * @param files
     * @return
     */
    @PostMapping("/upload")
    public Object upload(@RequestParam("files") MultipartFile[] files) throws IOException {
        //判空
        if (files == null){
            return AjaxResult.error("文件为空");
        }
        //判空
        if (files.length == 0){
            return AjaxResult.error("文件为空");
        }
        //定义存储集合
        List<FileVo> fileVos = new ArrayList<>();
        for (MultipartFile file : files) {
            //判文件大小
            if (file.getSize() /1024 /1024 > 500){
                return AjaxResult.error("文件大小超限");
            }
            //校验类型
            if (!verifyCustom(file)){
                return AjaxResult.error("文件类型错误");
            }
            //存储文件
            FileVo fileVo = sendMessageService.store(file.getInputStream(),file.getSize(),
                    file.getContentType(),file.getOriginalFilename());
            fileVos.add(fileVo);
        }
        return AjaxResult.success(fileVos);
    }


    /**
     * 文件下载
     * @param fileKey
     * @return
     */
    @GetMapping("/download")
    public void download(@RequestParam("key") String fileKey, HttpServletResponse response){
        //判空
        if (StringUtils.isBlank(fileKey)){
            throw new RuntimeException("文件标识为空");
        }
        //获取file
        FileVo fileVo = sendMessageService.findFile(fileKey);
        if (fileVo == null){
            throw new RuntimeException("文件为空");
        }
        try {
            //下载路径
            String downPath = String.valueOf(fileUploadPath.resolve(fileKey));
            //下载名称
            String fileName = fileVo.getFileName();
            //设置响应类型
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            //下载文件名重新编码
            FileUtil.setAttachmentResponseHeader(response,fileName);
            //输出文件
            FileUtil.writeBytes(downPath,response.getOutputStream());
        } catch (IOException e) {
            logger.error("下载文件失败: " + e);
        }
    }






    /**
     * 自定义文件类型验证
     */
    public boolean verifyCustom(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        //没有文件后缀
        if (index == -1) {
            return false;
        }
        String suffix = originalFilename.substring(index);
        //文件后缀不合法
        if (!Constant.FILE_TYPE.contains(suffix)) {
            return false;
        }
        return true;
    }

}
